'use client';

import { useToast } from '@/hooks/use-toast';
import trpc from '@/lib/trpc/client';
import { createOrder } from '@/service/actions/order';
import { useRouter } from 'next/navigation';
import { useState, useTransition } from 'react';
import { Button } from '../ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '../ui/dialog';
import { Label } from '../ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger } from '../ui/select';
import { Textarea } from '../ui/textarea';

export default function CreateOrder({
  shopId,
  disabled = false,
  cart,
}: {
  shopId: number;
  disabled?: boolean;
  cart: Record<string, number>;
}) {
  const [open, setOpen] = useState(false);
  const [isPending, startTransition] = useTransition();
  const { toast } = useToast();
  const [remark, setRemark] = useState('');
  const [addressId, setAddressId] = useState<number>();
  const { replace } = useRouter();
  const { data } = trpc.address.listAllAddresses.useQuery(undefined, {
    enabled: open,
  });

  const onSubmit = () => {
    const address = data?.find((item) => item.id === addressId);
    if (!address) return toast({ title: '请选择地址', variant: 'destructive' });
    startTransition(async () => {
      const { error, result: orderId } = await createOrder({
        shopId,
        address,
        remark,
        cart,
      });
      if (error) {
        toast({ title: error.message, variant: 'destructive' });
        return;
      }
      toast({ title: '创建订单成功' });
      replace(`/order/${orderId}`);
    });
  };

  return (
    <Dialog open={open}>
      <DialogTrigger asChild onClick={() => !disabled && setOpen(true)}>
        <Button disabled={disabled}>下单</Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>创建订单</DialogTitle>
          <DialogDescription className="hidden" />
        </DialogHeader>
        <Select onValueChange={(id) => setAddressId(Number(id))}>
          <SelectTrigger>
            {addressId
              ? data?.find((item) => item.id === addressId)?.address
              : '请选择地址'}
          </SelectTrigger>
          <SelectContent className="max-h-[400px] overflow-y-auto scrollbar-none">
            {data?.map((address) => (
              <SelectItem key={address.id} value={address.id.toString()}>
                <div className="space-y-1 hover:bg-muted transition-colors px-3 py-2 rounded-lg">
                  <div>{address.address}</div>
                  <div className="text-xs text-muted-foreground space-x-1">
                    <span>{address.name}</span>
                    <span>{address.phone}</span>
                  </div>
                </div>
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Label>备注</Label>
        <Textarea
          value={remark}
          onChange={(e) => setRemark(e.target.value)}
          className="resize-none"
          rows={3}
        />
        <div className="flex justify-end gap-2">
          <Button variant="outline" onClick={() => setOpen(false)}>
            取消
          </Button>
          <Button disabled={isPending} onClick={onSubmit}>
            {isPending && <span className="i-ri-loader-4-line animate-spin" />}
            下单
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
